<?php

/**
 * Model_Setpoint
 *
 */
 
require_once APPLICATION_PATH . '/models/DbTable/Room.php';
require_once APPLICATION_PATH . '/models/DbTable/RoomZone.php';
 
class Model_Setpoint
{
    /** Model_Table_Room */
    protected $_table;

    /**
     * Retrieve table object
     * 
     * @return Model_Room_Table
     */
    public function getTable()
    {
        if (null === $this->_table) {
            // since the dbTable is not a library item but an application item,
            // we must require it to use it
            require_once APPLICATION_PATH . '/models/DbTable/Setpoint.php';
            $this->_table = new Model_DbTable_Setpoint;
        }
        return $this->_table;
    }

    /**
     * Save a new setpoint
     * 
     * @param  array $data 
     * @return int|string
     */
    public function save(array $data)
    {
        $table  = $this->getTable();
        $fields = $table->info(Zend_Db_Table_Abstract::COLS);
        foreach ($data as $field => $value) {
            if (!in_array($field, $fields)) {
                unset($data[$field]);
            }
        }
        return $table->insert($data);
    }


    /**
     * Update a new setpoint
     * 
     * @param  array $data 
     * @return int|string
     */
    public function update(array $data)
    {
        $table  = $this->getTable();
        $fields = $table->info(Zend_Db_Table_Abstract::COLS);
        foreach ($data as $field => $value) {
            if (!in_array($field, $fields)) {
                unset($data[$field]);
            }
        }
        $room_id = $data["room_id"];
        $where = "room_id = $room_id";
        unset($data["room_id"]);
        return $table->update($data, $where);
    }

    public function fetchZones($room_id) 
    {
      //
      // TBD - this should be in RoomModel
      // 
      $table = $this->getTable();
      $select = $table->select()->where('room_id = ?', $room_id);
      
      $sp   = $table->fetchRow($select); 
      $room = $sp->findDependentRowset("Model_DbTable_Room");
      $zones = $room->current()->findDependentRowset("Model_DbTable_RoomZone");
      foreach ($zones as $zone) {
        $zone_ids[] = $zone->zone_id;
      }
      return  $zone_ids[0];
    }
    
    
    /**
     * Fetch an individual entry
     * 
     * @param  int|string $id 
     * @return null|Zend_Db_Table_Row_Abstract
     */
    public function fetchEntry($room_id)
    {
        $table = $this->getTable();
        
        $select = $table->select()->where('room_id = ?', $room_id);
        
        $sp   = $table->fetchRow($select); 
        $room = $sp->findDependentRowset("Model_DbTable_Room");

        $rs["setpoint"]  = $sp->setpoint;
        $rs["room_id"]   = $room->current()->room_id;
        $rs["room_name"] = $room->current()->name;

        return $rs;
    }
}